<?php
$username = trim($_POST['username']); //通过全局数组$_POST读取前端表单name为username的表单值
$usernameReg = "/^[a-zA-Z0-9]{3,10}$/";
if(!preg_match($usernameReg,$username)){
    echo "<script>alert('用户名只能是大小写字母、数字，长度为3-10！');history.back();</script>";
    exit;
}
$pw = trim($_POST['pw']);
$pwReg = "/^[A-Za-z0-9_\-*]{6,10}$/";
if(!preg_match($pwReg,$pw)){
    echo "<script>alert('密码只能是大小写字母、数字、_、-、*，长度为6-10！');history.back();</script>";
    exit;
}
$cpw = trim($_POST['cpw']);
if($pw !== $cpw){
    echo "<script>alert('密码和重复密码必须相同！');history.back();</script>";
    exit;
}
$email = trim($_POST['email']);
if($email){
    $emailReg = "/^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/";
    if(!preg_match($emailReg,$email)){
        echo "<script>alert('信箱格式不对！');history.back();</script>";
        exit;
    }
}
$sex = $_POST['sex'];
if($_POST['fav']){
    $fav = implode("，",$_POST['fav']);
}else{
    $fav = "";
}

$pw = md5($pw);
include 'coon.php';
//第三步，设置SQL语句
//判断用户名是否被占用
$sql = "select * from userinfo where username = '$username'";
$result = mysqli_query($conn,$sql); //返回的内容是一个结果集（记录集）
if(mysqli_num_rows($result)){
    echo "<script>alert('此用户名己被占用！');history.back();</script>";
    exit;
}
$sql = "insert into userinfo (username,pw,email,sex,fav) values ('$username','$pw','$email','$sex','$fav')";
//第四步，执行SQL查询语句
$result = mysqli_query($conn,$sql);
/*//调试数据库操作之第一招：打印SQL语句
echo $sql . "<br>";
//调试数据库操作之第二招：
echo mysqli_error($conn);
echo "<br>";*/
if($result){
    echo "<script>alert('数据插入成功！');history.back();</script>";
}
else{
    echo "<script>alert('数据插入失败！');history.back();</script>";
}
